/*
 * Message.cpp
 *
 *  Created on: 2020年11月30日
 *      Author: san
 */

#include "Message.h"
#include "Folder.h"


Message::Message(const Message &rhs): contents(rhs.contents), folders(rhs.folders)
{
	// 拷贝构造函数
	add_to_Folders(rhs);
}

Message &Message::operator=(const Message &rhs)
{
	// 重载赋值运算符
	remove_from_Folders();  // 更新已有的Folder(删除本Message)
	contents = rhs.contents;
	folders = rhs.folders;
	add_to_Folders(rhs);
}

Message &Message::operator=(Message &&m)
{
	// 移动赋值运算符
	if (this != &m)  // 直接检查自赋值情况
	{
		// 从Folders中删除本Message
		remove_from_Folders();
		contents = std::move(m.contents);
		move_Folders(&m);
	}
}

void Message::save(Folder &f)
{
	// 从指定的Folder中添加本Message
	folders.insert(&f);
	f.addMsg(this);
}

void Message::remove(Folder& f)
{
	// 从指定的Folder删除本Message
	folders.erase(&f);
	f.remMsg(this);
}

void Message::add_to_Folders(const Message &m)
{
	for (auto x: m.folders)
	{
		x->addMsg(this);
	}
}

void Message::remove_from_Folders()
{
	for (Folder *x: folders)
	{
		std::cout << "remove_from_Folders()" << std::endl;
		// 从Folder中删除
		x->remMsg(this);
	}
}

void Message::move_Folders(Message *m)
{
	// 从本Message移动folders
	folders = std::move(m->folders);
	for (auto f: folders)
	{
		f->remMsg(m);
		f->addMsg(this);
	}
	m->folders.clear();  // 确保销毁m是无害的
}

void Message::swap(Message &lhs, Message &rhs)
{
	using std::swap;
	// 先从对应的Folder中删除
	for (auto f: lhs.folders)
		f->remMsg(&lhs);
	for (auto f: lhs.folders)
		f->remMsg(&rhs);

	// 交换指针set和contents
	swap(lhs.contents, rhs.contents);
	swap(lhs.folders, rhs.folders);

	// 将消息添加进目录
	for (auto f: lhs.folders)
		f->addMsg(&lhs);
	for (auto f: rhs.folders)
		f->addMsg(&rhs);

}

Message::~Message() {
	// TODO Auto-generated destructor stub
	std::cout << "~Message()" << std::endl;
	remove_from_Folders();
	std::cout << "~Message()" << std::endl;
}

